<?php

namespace App\Exports;

use App\Models\FreightWay;
use App\Models\Machine;
use DB;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Illuminate\Contracts\Support\Responsable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;

class defectExport implements Responsable, FromQuery, WithMapping, WithHeadings, WithTitle, ShouldAutoSize
{

	use Exportable;

	private $fileName = '缺货商品';

	protected $days;

    public function withinDays($days)
    {
        $this->days = $days;
        $this->fileName = $this->days.'.xlsx';
        return $this;
    }

    public function query()
    {
        $user = auth('admin')->user();
    	if($user->type == 1){
    		$machines = Machine::query()->pluck('id');
    	}else{
    		$machines = optional($user->machine)->pluck('id');
    	} 
    	$freights = FreightWay::query()->with(['goods' => function($query){
    		$query->select('id', 'goods_name','goods_image');
    	}])->whereIn('machine_id', $machines)
    	   ->where('goods_id', '<>', 0)
    	   ->whereRaw('capacity > stock')
    	   ->select('*',DB::raw("sum(capacity) as capacity_num"),DB::raw("sum(stock) as stock_num"))
    	   ->groupBy('goods_id')
    	   ->orderBy('id', 'desc');
    	return $freights;
    }

    public function map($freight): array
    {
        return [
        	optional($freight->goods)->goods_name,
        	$freight->capacity_num,
        	$freight->stock_num,
            ($freight->capacity_num - $freight->stock_num),
        ];
    }

    public function headings(): array
    {
        return [
            '商品名称',
            '总容量',
            '总库存',
            '总缺货',
        ];
    }

    public function title(): string
    {
        return '缺货商品';
    }
}
